package net.pimpas.web.tests.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import net.pimpas.persistence.hibernate.serviceprovider.HibernateServiceProvider;
import net.pimpas.persistence.hibernate.serviceprovider.HibernateServiceProviderFactoryImpl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionException;

public class PersistenceFilter implements Filter {

	public void destroy() {
		
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(request instanceof HttpServletRequest)
			this.savePersistenceSession((HttpServletRequest) request);
		
		chain.doFilter(request, response);
	}
	
	
	private void savePersistenceSession( HttpServletRequest request ) {
		if(request.getSession().getAttribute(Session.class.getSimpleName()) != null) return;
		HibernateServiceProvider persistence = HibernateServiceProviderFactoryImpl.getPersistenceServiceProvider();
		try {
			Session session = persistence.getSessionFactory().openSession();
			request.getSession(true).setAttribute(Session.class.getSimpleName(), session);
		} catch (SessionException e) {
			e.printStackTrace();
		} catch (HibernateException e) {
			e.printStackTrace();
		}
	}

	public void init(FilterConfig config) throws ServletException {
		
	}
}